# -*- coding: utf-8 -*-

# Copyright 2013 Naman Kohli, Ida Leter, adapted from Fanficdownloader
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Correct way of reading from ACM since it does not allow normal urlib operations without user agent
##url = 'http://dl.acm.org/citation.cfm?id=331403.331405'
##req = u2.Request(url, headers={'User-Agent' : "Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1"})
##try:
##    data = u2.urlopen(req).read()


import time
import logging
logger = logging.getLogger(__name__)
import re
import urllib2

from .. import BeautifulSoup as bs
from .. import exceptions as exceptions
from ..htmlcleanup import stripHTML

from base_adapter import BaseSiteAdapter,  makeDate

def getClass():
    return ACMAdapter


logger = logging.getLogger(__name__)

class ACMAdapter(BaseSiteAdapter):

    def __init__(self, config, url):
        BaseSiteAdapter.__init__(self, config, url)

        self.decode = ["utf8","Windows-1252"]
        self.username = "" # if left empty, site doesn't return any message at all.
        self.password = ""

        # get paperId
        try:
            self.paper.setMetadata('paperId',self.parsedUrl.query.split('id=',)[1])
        except:
            self.paper.setMetadata('paperId',self.parsedUrl.path.split('/',)[2])

        # normalized URL.
        self._setURL('http://' + self.getSiteDomain() + '/citation.cfm?id='+self.paper.getMetadata('paperId'))

        # Each adapter needs to have a unique site abbreviation.
        self.paper.setMetadata('siteabbrev','acm')

        # The date format will vary from site to site.
        # http://docs.python.org/library/datetime.html#strftime-strptime-behavior
        self.dateformat = "%d/%m/%Y"

    @staticmethod # must be @staticmethod, don't remove it.
    def getSiteDomain():
        # The site domain.  Does have www here, if it uses it.
        return 'dl.acm.org'

    def getSiteExampleURLs(self):
        return "http://dl.acm.org/citation.cfm?id=331405"

    def getSiteURLPattern(self):
        return r"http://dl.acm.org/citation.cfm\?id=\d+"


    def needToLoginCheck(self, data):
        if 'Buy this Article' in data:
            return True
        else:
            return False

    def extractMetadata(self):
        req = urllib2.Request(self.url, headers={'User-Agent' : "Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1"})
        try:
            data = urllib2.urlopen(req).read()
        except urllib2.HTTPError, abstract:
            if e.code == 404:
                raise exceptions.PaperDoesNotExist()
            else:
                raise e


        # use BeautifulSoup HTML parser to make everything easier to find.
        soup = bs.BeautifulSoup(data, selfClosingTags=('p','strong'))

        # Now go hunting for all the meta data and the chapter list.
        # Title
        a = soup.find('meta', {'name' : 'citation_title'})
        self.paper.setMetadata('title',a['content'])

        # Author
        alist = soup.findAll('a', href=re.compile(r"author_page.cfm\?id*"))
        for a in alist:
            self.paper.addToList('author',unicode(stripHTML(a)))
            self.paper.addToList('authorUrl',a['href'])


        # Date
        a = soup.find('meta', {'name' : 'citation_date'})
        self.paper.setMetadata('datePublished', makeDate(a['content'], self.dateformat))

        # Abstract
        paperID = self.url.split("=")
        abstract_url = 'http://'+self.getSiteDomain() + '/tab_abstract.cfm?id=' + paperID[1]
        req = urllib2.Request(abstract_url, headers={'User-Agent' : "Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1"})
        try:
            abstract = urllib2.urlopen(req).read()
        except urllib2.HTTPError, abstract:
            pass
        self.paper.setMetadata('abstract',abstract)


        if self.needToLoginCheck(data):
            # need to log in for this one.
            print "Logging in is not supported. No pdf is downloaded"
        else:
            pdf = soup.find('meta',{'name' : 'citation_pdf_url'})
            self.paper.setMetadata('pdfurl',pdf['content'])

        # doi
        a = soup.find('meta', {'name' :'citation_doi'})
        if a != None:
            self.paper.setMetadata('doi',a['content'])


        # Publisher
        a = soup.find('meta', {'name' :'citation_publisher'})
        if a!= None:
            self.paper.setMetadata('publisher',a['content'])

        # Some metadata that can be added since its available through ACM

##        bibtex_url = self.getSiteDomain + '/exportformats.cfm?id=' + paperID[1] + '&expformat=bibtex'
##        req = u2.Request(bibtex_url, headers={'User-Agent' : "Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1"})
##        try:
##            bibtex = u2.urlopen(req).read()
##        except u2.HTTPError, abstract:
##            pass
##
##        self.paper.setMetadata('bibtex',bibtex)
##
##        endnotes_url = self.getSiteDomain + '/exportformats.cfm?id=' + paperID[1] + '&expformat=endnotes'
##        req = u2.Request(endnotes_url, headers={'User-Agent' : "Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1"})
##        try:
##            endnotes = u2.urlopen(req).read()
##        except u2.HTTPError, abstract:
##            pass
##
##        self.paper.setMetadata('endnotes',endnotes)
##
##
##        acmref_url = self.getSiteDomain + '/exportformats.cfm?id=' + paperID[1] + '&expformat=acmref'
##        req = u2.Request(acmref_url, headers={'User-Agent' : "Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1"})
##        try:
##            acmref = u2.urlopen(req).read()
##        except u2.HTTPError, abstract:
##            pass
##
##        self.paper.setMetadata('acmref',acmref)
